package com.example.administrator.my_musicplayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/10/20.
 */

public  class MusicService extends Service {

    public static final int COMMAND_UNKNOWN = -1;
    public static final int COMMAND_PLAY = 0;
    public static final int COMMAND_PAUSE = 1;
    public static final int COMMAND_STOP = 2;
    public static final int COMMAND_RESUME = 3;
    public static final int COMMAND_PREV = 4;
    public static final int COMMAND_NEXT = 5;
    public static final int COMMAND_CHECK_IS_PLAYING = 6;
    public static final int COMMAND_SEEK_TO = 7;

    public static final int STATUS_PLAYING = 0;
    public static final int STATUS_PAUSED = 1;
    public static final int STATUS_STOPPED = 2;
    public static final int STATUS_COMPLETED = 3;

    public static final String BROADCAST_MUSICSERVICE_CONTROL = "MusicService.ACTION_CONTROL";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS = "MusicService.ACTION_UPDATE";

    private int status;
    private int number = 0;

    public static int CIRCULATION_MODE = 2;
    private MediaPlayer player = new MediaPlayer();


    private CommandReceiver receiver;

    public void onCreate(){
        bindCommandReceiver();
        status = MusicService.STATUS_STOPPED;
    }

    public void onDestroy() {
        if (player != null) {
            player.release();
        }

        super.onDestroy();
    }

    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }


    private void bindCommandReceiver() {
        receiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter(BROADCAST_MUSICSERVICE_CONTROL);
        registerReceiver(receiver, filter);
    }


    class CommandReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            //获取命令
            int command = intent.getIntExtra("command", COMMAND_UNKNOWN);
            //执行命令
            switch (command) {
                case COMMAND_SEEK_TO:
                    seekTo(intent.getIntExtra("time",0));
                case COMMAND_PLAY:
                    number = intent.getIntExtra("number", 0);
                    play(number);
                    break;
                case COMMAND_PREV:
                    moveNumberToPrevious();
                    break;
                case COMMAND_NEXT:
                    moveNumberToNext();
                    break;
                case COMMAND_PAUSE:
                    pause();
                    break;
                case COMMAND_STOP:
                    stop();
                    break;
                case COMMAND_RESUME:
                    resume();
                    break;
                case COMMAND_CHECK_IS_PLAYING:
                    if (player != null && player.isPlaying()) {
                        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                    }
                    break;
                case COMMAND_UNKNOWN:
                default:
                    break;
            }
        }
    }

    private void sendBroadcastOnStatusChanged(int status) {
        Intent intent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status", status);
        if (status!=STATUS_STOPPED){
            intent.putExtra("time",player.getCurrentPosition());
            intent.putExtra("duration",player.getDuration());
            intent.putExtra("nemeber",number);
            intent.putExtra("musicName",MusicList.getMusicarray().get(number).getmusicName());
            intent.putExtra("musicArtist",MusicList.getMusicarray().get(number).getmusicArtist());
        }

        sendBroadcast(intent);
    }



    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicarray().get(number).getmusicPath());
            player.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        player.setOnCompletionListener(completionListener);
    }

    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer player) {
//            if (player.isLooping()) {
//                replay();
//            } else {
//                sendBroadcastOnStatusChanged(MusicService.STATUS_COMPLETED);
//            }

            {
                if (CIRCULATION_MODE == 0) { //单曲循环
                    player.start();
                    sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                } else if (CIRCULATION_MODE == 2) { //全部循环
                    number++;
                    if (number > MusicList.getMusicarray().size() - 1) {
                        number = 0;
                    }
                    Intent sendIntent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
                    // 发送广播，将被MainActivity组件中的BroadcastReceiver接收到
                    sendIntent.putExtra("number", number);
                   // path = MusicList.getMusicList().get(number).getMusicPath();
                    play(number);
                } else if (CIRCULATION_MODE == 1) { // 顺序播放
                    number++;  //下一首位置
                    if (number <= MusicList.getMusicarray().size() - 1) {
                        Intent sendIntent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
                        sendIntent.putExtra("number", number);
                        // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                       // path = MusicList.getMusicList().get(number).getMusicPath();
                        play(number);
                    } else {
                        player.seekTo(0);
                        number = 0;
                        Intent sendIntent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
                        sendIntent.putExtra("number", number);
                        // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                    }
                } else if (CIRCULATION_MODE == 3) {    //随机播放
                    number = getRandomIndex(MusicList.getMusicarray().size() - 1);
                    System.out.println("currentIndex ->" + number);
                    Intent sendIntent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
                    sendIntent.putExtra("number", number);
                    // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                   // path = MusicList.getMusicList().get(number).getMusicPath();
                    play(number);
                }
            }
        }
    };

    /** 获取随机位置*/
    protected int getRandomIndex(int end) {
        int index = (int) (Math.random() * end);
        return index;
    }
    private void moveNumberToNext() {
        // 判断是否到达列表底端
        if ((number ) == MusicList.getMusicarray().size()-1) {
            Toast.makeText(MusicService.this,"已达到列表底端",Toast.LENGTH_SHORT).show();
        } else {
            ++number;
            play(number);
        }
    }

    /** 选择上一首*/
    private void moveNumberToPrevious() {
        // 判断是否到达列表顶端
        if (number == 0) {
            Toast.makeText(MusicService.this,"已达到列表顶端",Toast.LENGTH_SHORT).show();
        } else {
            --number;
            play(number);
        }
    }
    /** 播放音乐*/
    private void play(int number) {
        // ֹֹͣͣ停止当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }
    /** 暂停音乐*/
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
            status = MusicService.STATUS_PAUSED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_PAUSED);
        }
    }

    /** 停止播放*/
    private void stop() {
        if (status != MusicService.STATUS_STOPPED) {
            player.stop();
            status = MusicService.STATUS_STOPPED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_STOPPED);
        }
    }

    /** 恢复播放（暂停之后）*/
    private void resume() {
        player.start();
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    /** 重新播放（播放完成之后）*/
    private void replay() {
        player.start();
        status = MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }




    private void seekTo (int time){
        player.seekTo(time);


    }



}
